<?php

namespace App\Api\CatchOrder;

use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

/**
 * 快手应用 抓单]
 * 上线时需注意
 * 1: 更新token目前没更新
 * 2: 目前未获取到用户的身份信息
 */
class Kwai
{
    public $appKey;
    public $appSecret;
    public $signSecret;
    public $syncAPIClient;
    public $serverHost = "https://open.kwaixiaodian.com/";
    public $webSite = '1688';
    // public $access_token = 'ChFvYXV0aC5hY2Nlc3NUb2tlbhJAm-9Sn3TLKQ1OcDnfgD10Q93Uah-qv7M0RpVj85rpxQSgGfL-UMIfvkHLHGaaGRu34YjBGWThZBfwWKcf0zZudhoSIEH75Kg-RaqlrUNstFhsUg4wIiDD81R9y_vG3jtIZpBFP3mHMgYziMbGeDKoj1zUQVg__ygFMAE';
    public $access_token = 'ChFvYXV0aC5hY2Nlc3NUb2tlbhJAOa6QTpTCpZOy70p8qGM6HndyXCqOLLICd4q5Il6C9tqiNGXkz0sLHN6eft_3rTzA7-Ec8t2n08zaXp6jgByowxoSKMdmjD9TQIWA4cxc70QihgBtIiA4nn8j7O0csRj-Y30LINsVZpJfutgWso6NH9ESrph6NSgFMAE';
    public $debug = false;
    public $shop_id;
    public $log;
    public $root;
    public function __construct($shop_id = '', $appKey = '', $appSecret = '', $signSecret = '')
    {
        $this->log = new Logger('CatchKwai');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/CatchKwai.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );

        $this->root = new Logger('DouYinRootLog');
        $this->root->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/CatchKwaiRootLog.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        !empty($appKey) and $this->appKey = $appKey;
        !empty($appSecret) and $this->appSecret = $appSecret;
        !empty($signSecret) and $this->signSecret = $signSecret;
        !empty($shop_id) and $this->shop_id = $shop_id;
    }
    public function getOrderList($data = [])
    {
        !isset($data['orderViewStatus']) and $data['orderViewStatus'] = 3;
        !isset($data['pageSize']) and $data['pageSize'] = 50;
        !isset($data['beginTime']) and $data['beginTime'] = $this->getMillisecond() - (30 * 60 * 1000);
        !isset($data['endTime']) and $data['endTime'] = $this->getMillisecond();
        $pr_arr = [
            //必选参数=============================================
            'orderViewStatus' => $data['orderViewStatus'],
            //订单状态，0未知 1 全部 2 待付款 3 待发货 4 待收货（已发货）5 已收货 6 交易成功订单 7 已关闭订单
            'pageSize' => $data['pageSize'],
            //每页请求数量 最多一页50条
            'beginTime' => $data['beginTime'],
            //订单生成时间的开始时间，单位毫秒， 不能小于90天前，且需要小于结束时间
            'endTime' => $data['endTime'],
            //订单生成时间的截止时间，单位毫秒，与开始时间的时间范围不大于7天
            'cursor' => '',
            //游标内容 第一次传空串，之后传上一次的cursor返回值，若返回“nomore”则标识到底


            //可选参数=============================================
            // 'sort' => 1,
            // //1时间降序 2时间升序 默认降序
            // 'queryType' => 1,
            // //	1按创建时间查找 2按更新时间查找 默认创建时间
            // 'cpsType' => 0, //分销类型 0-全部 1-普通订单 2-分销订单

        ];
        $res = $this->api('open.order.cursor.list', $pr_arr);
        var_dump($res);

        $paramsabc = [];

        if ($res['code'] == 1 and $res['msg'] == 'success') {

            if (!empty($res['data']['orderList'])) {
                foreach ($res['data']['orderList'] as $v) {
                    $paramsabc[] = [
                        'user_name' => $v['orderBaseInfo']['buyerNick'],
                        'card_num' => '',
                        'user_phone' => $v['orderAddress']['mobile'],
                        'order_num' => $v['orderItemInfo']['num'],
                        'province' => $v['orderAddress']['province'],
                        'city' => $v['orderAddress']['city'],
                        'area' => $v['orderAddress']['address'],
                        //=================接口未返回区字段
                        'street' => $v['orderAddress']['district'],
                        'addr' => $v['orderAddress']['address'],
                        'author_id' => '',
                        'author_name' => '',
                        'c_biz_desc' => '',
                        'product' => '',
                        'package_name' => $v['orderItemInfo']['skuNick'],
                        // 套餐名称
                        'status' => '',
                        // 状态
                        'created_at' => '',
                        'douyin_status_name' => ''
                    ];
                }
            }
        }
        // echo '<pre>';
        // // print_r($res['data']['orderList']);
        // print_r($paramsabc);

        // echo '</pre>';
        // exit;

        // print_r($paramsabc);

        return $paramsabc;
    }
    public function getOrderDetail($data = [])
    {
        $pr_arr = [
            //必选参数
            'oid' => $data['pid'], //订单id
        ];
        $res = $this->api('open.order.detail', $pr_arr);
        var_dump($res, 2222222222);
        $paramsabc = [];
        if ($res['code'] == 1 and $res['msg'] == 'success') {
            $paramsabc = [
                'user_name' => $res['data']['orderAddress']['consignee'],
                'card_num' => '',
                'user_phone' => $res['data']['orderAddress']['mobile'],
                'order_num' => $res['data']['orderBaseInfo']['oid'],
                'province' => $res['data']['orderAddress']['province'],
                'city' => $res['data']['orderAddress']['city'],
                'area' => $res['data']['orderAddress']['district'],
                //=================接口未返回区字段
                'street' => $res['data']['orderAddress']['district'],
                'addr' => $res['data']['orderAddress']['address'],
                'author_id' => $res['data']['orderCpsInfo']['distributorId'],
                'author_name' => $res['data']['orderCpsInfo']['distributorName'],
                'c_biz_desc' => '',
                'product' => $res['data']['orderItemInfo']['skuNick'],
                'package_name' => $res['data']['orderItemInfo']['skuNick'],
                // 套餐名称
                'status' => '',
                // 状态
                'created_at' => '',
                'douyin_status_name' => ''
            ];
        }

        return $paramsabc;
    }
    public function orderDeliver()
    {
        $pr_arr = [
            //必选参数=============================================
            'expressNo' => 'SF1233',
            //快递单号
            'expressCode' => 123,
            //快递公司code，由https://open.kwaixiaodian.com/docs/dev?pageSign=3d4aa40abaab83c4a5f5839f6848dcb71614264033704获取
            'orderId' => '',
            //订单编号


            //可选参数=============================================
            'returnAddressId' => 295440542222, //商家退货地址，可从查询商家地址列表API-open.address.seller.list中获取退货地址
            // 'qualityParam' => {"reportUrl":"reportUrlValue","qualityInspectionNo":"qualityInspectionNoValue","sn":"snValue"},//质检信息专用非必填，发货可忽略

        ];
        $res = $this->api('open.seller.order.goods.deliver', $pr_arr);
        if ($res['code'] == 1 and $res['msg'] == 'success') {
            return true;
        } else {
            return false;
        }
    }
    //解密  暂时不上
    public function decrypt()
    {
        $pr_arr = [
            'batchDecryptList' => [[
                'encryptedData' => '$2VdNkUbrtNmYeaafVVMgzjfc7Nu9McPW/RDLN7P5wEU=$Ci1tZXJjaGFudC5vcGVuLnNlY3JldC5rZXkua3M3MTE1Njg3NDM5ODU5NzQ3MDYSINBV5EJzfu2p64bU7kIUZmVOKfr23p6N/YDyFxmO34tVGhJieB2DamRFrughvWiOfRBUtLAiIBsnjLI191tQ4zIaD7Pwmt1py568YfbvryOOxSEDdsL+KAUwAQ==&Ci1tZXJjaGFudC5vcGVuLnNlY3JldC5rZXkua3M3MTE1Njg3NDM5ODU5NzQ3MDYSMEbgiFzBS5E4+xwJNUM+mNRrAvQ0BgOHKYewPL4LGcjzB99eBCDYVAo2hnSWM9ZrNxoSp0gWibUpNdGLoHw9mLBW6ZzVIiCCMI2on3ChxAKjUHn45Q9ByqWA20H2GoSMTGZ2FxVM3CgFMAE=$1$$',
                'bizId' => '2321900030360552',
            ]]
        ];
        $res = $this->api('open.order.decrypt.batch', $pr_arr);
        var_dump($res);
        if ($res['code'] == 1 and $res['msg'] == 'success') {
            return true;
        } else {
            return false;
        }
    }
    public function refreshToken($refreshToken)
    {
        $url = "https://openapi.kwaixiaodian.com/oauth2/refresh_token?app_id=" . env('KS.appKey') . "&app_secret=" . env('KS.appSecret') . "&refresh_token={$refreshToken}&grant_type=refresh_token";
        $s = $this->curl_https_get($url);
        $s = json_decode($s, true);
        return $s;
    }
    // https://open.kwaixiaodian.com/oauth/authorize?app_id=1972152495&redirect_uri=https://adminnew.chenqiwangluo.com/api/v1/getPddCode&state=79&scope=merchant_order&response_type=code&state=12
    // https://adminnew.chenqiwangluo.com/api/v1/getPddCode&state=79
    // https://open.kwaixiaodian.com/oauth/authorize?app_id=ks7115687439859747060&redirect_uri=https://adminnew.chenqiwangluo.com/api/v1/getPddCode&scope=merchant_shop,merchant_refund,merchant_funds,merchant_item,merchant_order,user_info,merchant_video,merchant_promotion,merchant_user,merchant_comment,merchant_logistics&response_type=code
    // https://open.kwaixiaodian.com/oauth/authorize?app_id=ks7115687439859747060&redirect_uri=http%3A%2F%2F47.104.168.226%3A1888%2Fapi%2Fv1%2FgetKwaiCode&scope=merchant_shop,merchant_refund,merchant_funds,merchant_item,merchant_order,user_info,merchant_video,merchant_promotion,merchant_user,merchant_comment,merchant_logistics&response_type=code
    public function getToken($code, $redirectUrl = '')
    {

        $url = $this->serverHost . "oauth2/access_token?app_id={$this->appKey}&app_secret={$this->appSecret}&code={$code}&grant_type=authorization_code";

        // $s = json_decode($s, true);
        // return $s;
    }

    public function api($apiType, $param, $method = 'get')
    {
        $arr['appkey'] = $this->appKey;
        $arr['version'] = '1';
        $arr['access_token'] = $this->access_token;
        $arr['timestamp'] = $this->getMillisecond();
        $arr['method'] = trim($apiType);
        $arr['param'] = $param ? json_encode($param) : '{}';
        $arr['signMethod'] = 'MD5';
        ksort($arr); // 排序
        $arr['sign'] = $this->getSign($arr, $this->signSecret);
        $apiInfo = str_replace('.', '/', $arr['method']);
        $url = $this->serverHost . $apiInfo;

        if ($method == 'get') {
            $s = $this->curl_https_get($url . '?' . http_build_query($arr, '', '&'), $param);
        } else {
            $s = $this->curl_https_post($url, $arr);
        }
        if (empty($s['data'])) {
            return $s['error'];
        }
        // var_dump($s);
        $s = json_decode($s['data'], true);
        return $s;
    }
    public function getSign($params, $key)
    {
        $unSignParaString = $this->formatQueryParaMap($params, false);
        $signStr = (md5($unSignParaString . "&signSecret=" . $this->signSecret));
        return $signStr;
    }

    public function formatQueryParaMap(array $paraMap, $urlEncode = false)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v) {
            if (null != $v && "null" != $v) {
                if ($urlEncode) {
                    $v = urlencode($v);
                }
                $buff .= $k . "=" . $v . "&";
            }
        }
        $reqPar = '';
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff) - 1);
        }
        return $reqPar;
    }

    /*获取13位时间戳*/
    public static function getMillisecond()
    {
        list($t1, $t2) = explode(' ', microtime());
        return sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }

    private function curl_get_contents($url, $data = array(), $https = false)
    {
        $results['error'] = '';
        $results['status'] = 0;
        $results['data'] = array();
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        $curl = curl_init(); // 启动一个CURL会话
        if (!empty($data) && is_array($data)) {
            curl_setopt($curl, CURLOPT_POST, TRUE);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
            curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
        }
        if ($https) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
            curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转

        }
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_USERAGENT, $user_agent); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        $results['data'] = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            $results['error'] = curl_error($curl); //捕抓异常
            var_dump($results, 111111111);
        }
        curl_close($curl); // 关闭CURL会话
        $this->log->info('参数:' . json_encode($data) . '返回结果:' . json_encode($results));
        return $results; // 返回数据

    }
    public function curl_https_post($url, $data)
    {
        return $this->curl_get_contents($url, $data, true);
    }
    public function curl_https_get($url)
    {
        return $this->curl_get_contents($url, array(), true);
    }
}
